// --------------------------------------------------------------------------------------------------------------------
// <copyright file="FileRecorderProxy.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Microsoft.Robotics.Runtime
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;

    /// <summary>
    /// Agent that records to a file the specified message types produced by a given producer.
    /// </summary>
    [DataContract]
    [System.Diagnostics.CodeAnalysis.SuppressMessage(
    "Microsoft.Design",
    "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
    Justification = "Agents clean up resources when OnDeactivated() is called")]
    public class FileRecorderProxy : Agent, ISubscriptionReceiver
    {
        /// <summary>
        /// The name of the agent this proxy subscribes to (i.e. the agent to network-enable or the agent to record).
        /// </summary>
        [DataMember(Name = "Producer")]
        private readonly string producer;

        /// <summary>
        /// The file path for file proxy player agent.
        /// </summary>
        [DataMember(Name = "Path")]
        private readonly string filePath;

        /// <summary>
        /// The types of messages published by the player.
        /// </summary>
        [DataMember(Name = "MessageTypes")]
        private readonly Type[] messageTypes;

        /// <summary>
        /// The type of xml serialization. True for binary, false for xml.
        /// </summary>
        [DataMember(Name = "BinarySerialization")]
        private readonly bool binarySerialization;

        /// <summary>
        /// If true, arrays are compressed. Only meaningful for recorder / near-proxy, as the compression information is saved with the array.
        /// </summary>
        [DataMember(Name = "EnableArrayCompression")]
        private readonly bool enableArrayCompression;

        /// <summary>
        /// The agent host that wraps the agent we are exposing
        /// </summary>
        private IAgentHost partnerAgentHost;

        /// <summary>
        /// The FileWriter to write file to disk
        /// </summary>
        private SerializedFileWriter writer;

        /// <summary>
        /// Initializes a new instance of the FileRecorderProxy class
        /// </summary>
        /// <param name="name">The name of the recorder agent.</param>
        /// <param name="filePath">The path to the file to record.</param>
        /// <param name="messageTypes">The types of messages recorded by this agent.</param>
        /// <param name="producer">The agent to subscribe tom whose messages the recorder will serialize.</param>
        /// <param name="binarySerialization">Value indicating whether to use binary xml serialization (true) or xml serialization(false)</param>
        /// <param name="enableArrayCompression">Optional. If true, arrays are compressed. Defaults to false.</param>
        public FileRecorderProxy(
            string name,
            string filePath,
            Type[] messageTypes,
            string producer,
            bool binarySerialization = true,
            bool enableArrayCompression = false)
            : base(name)
        {
            this.filePath = filePath;
            this.messageTypes = messageTypes;
            this.producer = producer;
            this.binarySerialization = binarySerialization;
            this.enableArrayCompression = enableArrayCompression;
        }

        /// <summary>
        /// Gets the set of message types supported by this writer.
        /// </summary>
        public IEnumerable<Type> SubscriptionTypes
        {
            get { return this.messageTypes; }
        }

        /// <summary>
        /// Initializes the file writer.
        /// </summary>
        /// <param name="locator">A locator that can be used to find other agents.</param>
        public override void Initialize(AgentLocator locator)
        {
            base.Initialize(locator);
            this.partnerAgentHost = locator.GetAgent(this.producer);
            foreach (Type t in this.messageTypes)
            {
                this.partnerAgentHost.Subscribe(t, this);
            }
        }

        /// <summary>
        /// Called when the agent becomes active. Activates the partner agent.
        /// </summary>
        public override void OnActivated()
        {
            this.writer = new SerializedFileWriter(this.messageTypes, this.filePath, this.Name, this.binarySerialization, this.enableArrayCompression);
            base.OnActivated();
            this.partnerAgentHost.Activate();
        }

        /// <summary>
        /// Called to stop recording
        /// </summary>
        public override void OnDeactivated()
        {
            base.OnDeactivated();
            this.writer.Stop();
            this.partnerAgentHost.Deactivate();
        }

        /// <summary>
        /// Called to process the specified message.
        /// </summary>
        /// <param name="message">The message to write</param>
        public void Receive(AgentMessage message)
        {
            this.writer.Write(message);
        }
    }
}
